package cn.com.dhc.danlu.activity.delivery;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.myself.MyInvoiceActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.adapter.NormalInvoiceAdapter;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.response.mydl.invoice.InvoiceListResponse;
import cn.com.hd.mall.web.webservices.entity.response.mydl.invoice.InvoiceListResponse.InvoiceListModel;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/***
 * 选择发票页面  （提交订单页面--->发票信息--）
 *
 * @author wzf
 */
public class InvoiceMainActivity extends BaseActivity {
    /**
     * 返回按钮
     */
    protected LinearLayout llytBack;
    /**
     * Activity容器
     */
    private LinearLayout llytContainer;
    /**
     * 不开发票tab
     */
    private LinearLayout llytNoInvoice;
    /**
     * 普通发票tab
     */
    private LinearLayout llytNormalInvoice;
    /**
     * 增值税发票tab
     */
    private LinearLayout llytAddInvoice;
    /**
     * 不能开增值税发票txt
     */
    private TextView llytAddInvoicetxt;
    /**
     * 普通发票adapter
     */
    private NormalInvoiceAdapter adapter;
    /**
     * 接收普通发票类
     */
    private List<InvoiceListModel> normalInvoiceList;
    /**
     * 接收增值税发票类
     */
    private InvoiceListModel vatInvoice;
    /**
     * 确定按钮
     */
    private Button invoiceOk;
    /**
     * 意图对象
     */
    private Intent invoiceData;
    /**
     * 支持货到增值税发票
     */
    private String vatInvoiceSupport;
    /**
     * 修改发票
     */
    private TextView invoiceEdit;
    /**
     * 不能开增值税发票提示txt1
     */
    private TextView support3;
    /**
     * 不能开增值税发票提示txt2
     */
    private TextView support4;
    /**
     * 修改发票跳转intent
     */
    private Intent invoiceEditIntent;
    //从我的丹露返回的发票类型
    private int invoiceType;
    //从提交订单过来发票ID
    private String getInvoiceId;

    /**
     * 切换Tab监听。
     */
    private OnClickListener onTabClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                case R.id.llytNoInvoice:
                    invoiceOk.setVisibility(View.VISIBLE);
                    invoiceOk.setClickable(true);
                    invoiceEdit.setVisibility(View.GONE);
                    invoiceOk.setBackgroundResource(R.drawable.selector_button_press);
                    // 不开发票Tab
                    showNoInvoiceTab(v.getId());
                    invoiceData.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_NO_INVOICE);
                    break;

                case R.id.llytNormalInvoice:
                    invoiceOk.setClickable(true);
                    invoiceEdit.setVisibility(View.VISIBLE);
                    invoiceEditIntent.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_NORMAL_INVOICE);
                    invoiceOk.setBackgroundResource(R.drawable.selector_button_press);
                    // 普通发票Tab
                    showNormalInoviceTab(v.getId());
                    invoiceData.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_NORMAL_INVOICE);
                    break;

                case R.id.llytAddInvoice:
                    invoiceEdit.setVisibility(View.VISIBLE);
                    // 增值税发票Tab
                    showAddInvoiceTab(v.getId());
                    invoiceEditIntent.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_ADD_INVOICE);
                    invoiceData.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_ADD_INVOICE);
                    break;

                case R.id.invoiceOk: // 确定按钮
                    invoiceData.setClass(InvoiceMainActivity.this, OrderConfirmActivity.class); // 到“提交订单”页面
                    setResult(RESULT_OK, invoiceData);
                    finish();
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invoice_main);

        initViews();
        initData();
        setViews();
    }

    private void initViews() {
        llytBack = (LinearLayout) findViewById(R.id.llytBack);
        llytContainer = (LinearLayout) findViewById(R.id.llytContainer);
        llytNoInvoice = (LinearLayout) findViewById(R.id.llytNoInvoice);
        llytNormalInvoice = (LinearLayout) findViewById(R.id.llytNormalInvoice);
        llytAddInvoice = (LinearLayout) findViewById(R.id.llytAddInvoice);
        llytAddInvoicetxt = (TextView) findViewById(R.id.llytAddInvoicetxt);
        invoiceOk = (Button) findViewById(R.id.invoiceOk);
        invoiceEdit = (TextView) findViewById(R.id.invoiceEdit);
    }

    private void initData() {
        invoiceData = getIntent();
        vatInvoice = new InvoiceListModel();

        getInvoiceList(); //请求发票列表
    }

    /**
     * 请求发票列表
     */
    private void getInvoiceList() {
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.setToken(agent.getToken());
        agent.getApi()
                .getInvoiceList(baseRequest)
                .compose(OperatorUtils.<InvoiceListResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<InvoiceListResponse>(this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(InvoiceListResponse model) {
                        normalInvoiceList = model.getNormalInvoiceList();
                        vatInvoice = model.getVatInvoice();
                        showNoInvoiceTab(R.id.llytNoInvoice);
                        if (invoiceType == CommonConst.InvoiceConst.ID_NORMAL_INVOICE) {
                            showNormalInoviceTab(R.id.llytNormalInvoice);
                            invoiceEdit.setVisibility(View.VISIBLE);
                            invoiceEditIntent.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_NORMAL_INVOICE);
                        } else if (invoiceType == CommonConst.InvoiceConst.ID_ADD_INVOICE) {
                            invoiceEdit.setVisibility(View.VISIBLE);
                            showAddInvoiceTab(R.id.llytAddInvoice);
                            invoiceEditIntent.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_ADD_INVOICE);
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    /**
     * 返回前画面，画面有特殊需求复写该方法
     */
    protected void back() {
        // 返回前画面
        if (!CommonUtils.isStringBlank(getInvoiceId)) {
            if (normalInvoiceList == null || normalInvoiceList.size() == 0) {
                invoiceData.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_NO_INVOICE);
            } else {
                invoiceData.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_NORMAL_INVOICE);
                invoiceData.putExtra(CommonConst.IntentKey.INVOICE_NAME, normalInvoiceList.get(0).getInvoiceHeader());
                invoiceData.putExtra("invoiceId", normalInvoiceList.get(0).getInvoiceId());
            }
            invoiceData.setClass(InvoiceMainActivity.this, OrderConfirmActivity.class);
            setResult(RESULT_OK, invoiceData);
        }
        finish();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    /**
     * 画面初始化
     */
    private void setViews() {
        if (getIntent().getStringExtra(CommonConst.IntentKey.INVOICE_ID) != null) {
            getInvoiceId = getIntent().getStringExtra(CommonConst.IntentKey.INVOICE_ID);
        }
        // 显示首页Tab
        showNoInvoiceTab(R.id.llytNoInvoice);
        invoiceData.putExtra(CommonConst.IntentKey.INVOICE_ID, CommonConst.InvoiceConst.ID_NO_INVOICE);
        vatInvoiceSupport = getIntent().getStringExtra("VATSUPPT");
        if (vatInvoiceSupport == null) {
            vatInvoiceSupport = "-1";
        }
        invoiceEditIntent = new Intent();
        // 设置监听
        setListener();
    }

    /**
     * 设置监听
     */
    private void setListener() {
        setBaseActivityListener();
        llytNoInvoice.setOnClickListener(onTabClickListener);
        llytNormalInvoice.setOnClickListener(onTabClickListener);
        llytAddInvoice.setOnClickListener(onTabClickListener);
        invoiceOk.setOnClickListener(onTabClickListener);
        invoiceEdit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                invoiceEditIntent.setClass(InvoiceMainActivity.this, MyInvoiceActivity.class);
                startActivityForResult(invoiceEditIntent, 100);

            }
        });
    }

    /**
     * 普通发票tab
     */
    private void showNormalInoviceTab(int viewId) {
        // 设置Tab选中效果
        selectTabLayout(viewId);
        llytContainer.removeAllViews();
        View view = LayoutInflater.from(this).inflate(R.layout.layout_normal_invoice, null);
        // 有发票布局
        LinearLayout llytInvoice = (LinearLayout) view.findViewById(R.id.llytInvoice);
        // 没有发票布局
        LinearLayout llytNoNormalInvoice = (LinearLayout) view.findViewById(R.id.llytNoInvoice);
        if (normalInvoiceList == null || normalInvoiceList.size() == 0) {
            llytNoNormalInvoice.setVisibility(View.VISIBLE);
            llytInvoice.setVisibility(View.GONE);
            llytNoNormalInvoice.setLayoutParams(new LayoutParams(llytContainer.getWidth(), llytContainer.getHeight()));
            invoiceData.putExtra(CommonConst.IntentKey.INVOICE_NAME, "");
            invoiceOk.setVisibility(View.GONE);
        } else {
            invoiceOk.setVisibility(View.VISIBLE);
            ListView listView = (ListView) view.findViewById(R.id.lvInvoice);
            adapter = new NormalInvoiceAdapter(getApplicationContext(), normalInvoiceList);
            listView.setAdapter(adapter);
            String invoiceName = normalInvoiceList.get(0).getInvoiceHeader();
            String invoiceId = normalInvoiceList.get(0).getInvoiceId();
            adapter.setSelectedIndex(0);
            adapter.notifyDataSetChanged();
            invoiceData.putExtra(CommonConst.IntentKey.INVOICE_NAME, invoiceName);
            invoiceData.putExtra("invoiceId", invoiceId);
            listView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
                    adapter.setSelectedIndex(index);
                    adapter.notifyDataSetChanged();
                    String invoiceName = normalInvoiceList.get(index).getInvoiceHeader();
                    String invoiceId = normalInvoiceList.get(index).getInvoiceId();
                    invoiceData.putExtra(CommonConst.IntentKey.INVOICE_NAME, invoiceName);
                    invoiceData.putExtra("invoiceId", invoiceId);
                }
            });
        }

        llytContainer.addView(view);
    }

    /**
     * 没有发票tab
     */
    private void showNoInvoiceTab(int viewId) {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_no_invoice, null);
        llytContainer.removeAllViews();
        view.setLayoutParams(new LayoutParams(llytContainer.getWidth(), LayoutParams.WRAP_CONTENT));
        llytContainer.addView(view);
        // 设置Tab选中效果
        selectTabLayout(viewId);
    }

    /**
     * 增值税发票tab
     */
    private void showAddInvoiceTab(int viewId) {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_add_invoice, null);
        // 有发票布局
        LinearLayout llytNoInvoice = (LinearLayout) view.findViewById(R.id.llytNoInvoice);
        // 没有发票布局
        LinearLayout llytHasInvoice = (LinearLayout) view.findViewById(R.id.llytHasInvoice);
        support3 = (TextView) view.findViewById(R.id.support3);
        support4 = (TextView) view.findViewById(R.id.support4);
        if (vatInvoice == null) {
            invoiceEdit.setVisibility(View.VISIBLE);
            llytNoInvoice.setVisibility(View.VISIBLE);
            support3.setText(R.string.add_no_invoice_support3);
            support4.setText(R.string.add_no_invoice_support4);
            support3.setVisibility(View.VISIBLE);
            support4.setVisibility(View.VISIBLE);
            invoiceOk.setVisibility(View.GONE);
            llytHasInvoice.setVisibility(View.GONE);
            llytNoInvoice.setLayoutParams(new LayoutParams(llytContainer.getWidth(), llytContainer.getHeight()));
            invoiceData.putExtra(CommonConst.IntentKey.INVOICE_NAME, "");
        } else {
            invoiceEdit.setVisibility(View.VISIBLE);
            llytNoInvoice.setVisibility(View.VISIBLE);
            support3.setVisibility(View.VISIBLE);
            support4.setVisibility(View.VISIBLE);
            invoiceOk.setVisibility(View.GONE);
            llytHasInvoice.setVisibility(View.GONE);
            support3.setText(R.string.add_no_invoice_support1);
            support4.setText(R.string.add_no_invoice_support2);
            llytNoInvoice.setLayoutParams(new LayoutParams(llytContainer.getWidth(), llytContainer.getHeight()));
            invoiceData.putExtra(CommonConst.IntentKey.INVOICE_NAME, "");
        }
        llytContainer.removeAllViews();
        llytContainer.addView(view);

        // 设置Tab选中效果
        selectTabLayout(viewId);
    }

    /**
     * Tab选中效果
     *
     * @param viewId
     *         选中Tab的Id
     */
    private void selectTabLayout(int viewId) {

        // 不开发票Tab
        if (R.id.llytNoInvoice == viewId) {
            llytNoInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_checked));
        } else {
            llytNoInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_not_checked));
        }

        // 普通发票Tab
        if (R.id.llytNormalInvoice == viewId) {
            llytNormalInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_checked));
        } else {
            llytNormalInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_not_checked));
        }

        // 增值税发票Tab
        if (R.id.llytAddInvoice == viewId) {
            llytAddInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_checked));
        } else {
            llytAddInvoice.setBackgroundColor(getResources().getColor(R.color.invoice_not_checked));
        }
    }

    /**
     * 设置点击监听
     */
    private void setBaseActivityListener() {
        if (llytBack != null) {
            // 设置返回按钮点击监听
            llytBack.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // 返回前画面
                    back();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (resultCode) {
            case RESULT_OK:
                if (data != null) {
                    invoiceType = data.getIntExtra(CommonConst.IntentKey.INVOICE_ID, 2);
                    // 请求发票列表
                    getInvoiceList();
                }
                break;

            default:
                break;
        }
    }
}
